package com.lzh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.domain.entity.ItemConfig;
import com.lzh.domain.entity.User;
import com.lzh.domain.entity.UserBackpack;
import com.lzh.domain.vo.BadgeVO;
import com.lzh.mapper.UserMapper;
import com.lzh.service.UserBackpackService;
import com.lzh.service.UserService;
import com.lzh.service.cache.ItemCache;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 20143
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-07-05 16:24:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private ItemCache itemCache;

    @Resource
    private UserBackpackService userBackpackService;


    @Override
    public List<BadgeVO> getBadgeList(Long uid) {
        //获取所有的徽章
        List<ItemConfig> allItem = itemCache.getByType(2);

        //获取用户拥有所有的徽章
        List<UserBackpack> userBackpacks = userBackpackService.powerBadgeListByUid(uid, allItem.stream().map(ItemConfig::getId).collect(Collectors.toList()));

        //获取用户佩戴的徽章
        User user = getById(uid);

        if (Objects.isNull(user)) {
            //用户不存在
            return Collections.emptyList();
        }

        //获取用户拥有的徽章
        Set<Long> powerBadge = userBackpacks.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());

        //获取所有的徽章进行排序 先进行是否拥有进行排序，后对用户佩戴进行排序
        return allItem.stream().map(item -> {
            BadgeVO badgeVO = new BadgeVO();
            BeanUtils.copyProperties(item, badgeVO);
            badgeVO.setObtain(powerBadge.contains(item.getId()) ? 1 : 0);
            badgeVO.setWaring(Objects.equals(item.getId(), user.getItemId()) ? 1 : 0);
            return badgeVO;
        }).sorted(Comparator.comparing(BadgeVO::getObtain, Comparator.reverseOrder()).thenComparing(BadgeVO::getWaring, Comparator.reverseOrder())).collect(Collectors.toList());
    }
}




